
#include <cstring>
#include <iostream>
#include <string>
#include <unordered_map>

#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"

using namespace std;
using namespace LogModule;
enum class Status
{
    NEW,
    CONNECTING,
    CONNECTED,
    DISCONNECTED, // 失联
    CLOSED        // 重连失败
};
enum exitCode
{
    USAGE_ERR,
    SOCKER_ERR
};
class clientConnection
{
    const static int default_sockfd = -1;
    const static int default_retry_interval = 1;
    const static int default_max_retries = 5;

private:
    int _sockfd;
    uint16_t _serverport;
    std::string _serverip;
    Status _status;
    int _retry_interval; // 重试的时间
    int _max_retries;    // 重试的次数
public:
    clientConnection(std::string serverip, uint16_t serverport)
        : _sockfd(default_sockfd), _serverip(serverip),
          _serverport(serverport), _retry_interval(default_retry_interval),
          _max_retries(default_max_retries), _status(Status::NEW)
    {
    }
    void connect()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LogModule::LOG(LogLevel::FATAL) << "socket create error";
            exit(exitCode::SOCKER_ERR);
        }
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET;
        server.sin_port = ::htons(_serverport);
        inet_pton(AF_INET, _serverip.c_str(), &server.sin_addr);

        int n = ::connect(_sockfd, reinterpret_cast<sockaddr *>(&server), sizeof server);
        if (n < 0)
        {
            // 1. 连接失败， 先关闭 sockfd
            disconnect();
            // 2. 更新状态
            _status = Status::DISCONNECTED;
            // 3. 返回
            return;
        }
        _status = Status::CONNECTED;
        std::cout << "connect success" << std::endl;
    }
    void disconnect()
    {
        if (_sockfd > default_sockfd)
        {
            ::close(_sockfd);
            _sockfd = default_sockfd;
            _status = Status::DISCONNECTED;
        }
    }
    void reconnect()
    {
        _status = Status::CONNECTING;
        int cnt = 0;
        while (true)
        {
            connect();
            if (_status == Status::CONNECTED)
                return;
            cnt++;
            if (cnt > _max_retries)
            {
                _status = Status::CLOSED;
                std::cout << "重连失败， 请检查" << std::endl;
                break;
            }
            std::cout << "断线重连， 重连次数：" << cnt << std::endl;
            sleep(_retry_interval);
        }
    }
    void process() // 正常的io通信
    {
        while(true)
        {
            std::string message = "hello server";
            ssize_t n = ::send(_sockfd, message.c_str(), message.size(), 0);
            if (n > 0)
            {
                char buffer[1024];
                size_t m = ::recv(_sockfd, buffer, sizeof buffer, 0);
                if (m > 0)
                {
                    std::cout << "server echo# " << buffer << std::endl;
                }
                else
                {
                    _status = Status::DISCONNECTED;
                    break;
                }
            }
            else{
                std::cerr << "send error" << std::endl;
                _status = Status::CLOSED;
                break;
            }

            sleep(1);
        }
    }
    Status status() { return _status; }
    ~clientConnection()
    {
        
    }
};
class tcpClient
{
public:
    tcpClient(std::string serverip, uint16_t serverport)
        : _connection(serverip, serverport)
    {
    }
    ~tcpClient()
    {
    }
    void excute()
    {
        while (true)
        {
            switch (_connection.status())
            {
                // NEW,
                //  CONNECTING,
                //  CONNECTED,
                //  DISCONNECTED, // 失联
                //  CLOSED
            case Status::NEW:
                _connection.connect();
                break;
            case Status::CONNECTED:
                _connection.process();

                break;
            case Status::DISCONNECTED:
                _connection.reconnect();
                break;
            case Status::CLOSED:
                _connection.disconnect();
                return;
                break;
            default:
                // do nothing
                break;
            }
        }
    }

private:
    clientConnection _connection;
};
void Usage(const std::string &&process)
{
    std::cout << "usage: " << process << " serverip serverport" << std::endl;
}
// tcp_client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(exitCode::USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    tcpClient tcpclient(serverip, serverport);
    tcpclient.excute();
    return 0;
}
